package com.wxjfkg.workflow.impl;

import java.util.Date;
import java.util.List;

import org.activiti.engine.delegate.DelegateExecution;
import org.apache.commons.lang.time.DateUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.fivestar.credit.service.CreditApplyInfoService;
import com.fivestar.credit.service.CreditLimitService;
import com.fivestar.credit.service.vo.CreditApplyInfoDetailDto;
import com.fivestar.credit.service.vo.CreditApplyInfoDto;
import com.fivestar.credit.service.vo.CreditConstants;
import com.fivestar.credit.service.vo.CreditLimitDto;
import com.fivestar.creditperson.service.CreditUserLimitService;
import com.fivestar.creditperson.service.vo.CreditUserLimitDto;
import com.fivestar.merchant.service.MerchantService;
import com.fivestar.merchant.service.vo.MerchantConstants;
import com.fivestar.merchant.service.vo.MerchantRelatedDto;
import com.fivestar.merchant.service.vo.MerchantSettleAccountDto;
import com.fivestar.query.vo.ResultDto;
import com.wxjfkg.workflow.BeforeEndTaskService;

@Service("creditApplySuccessTaskServiceImpl")
public class CreditApplySuccessTaskServiceImpl implements BeforeEndTaskService {

	public Logger logger = LoggerFactory.getLogger(CreditApplySuccessTaskServiceImpl.class);
	
	//更新授信额度信息
	@Autowired
	private CreditLimitService creditLimitService;
	@Autowired
	private CreditUserLimitService creditUserLimitService;
	@Autowired
	private CreditApplyInfoService creditApplyInfoService;
	@Autowired
	private MerchantService merchantService;

	@Override
	@Transactional(value="txTranManager")
	public void execute(DelegateExecution execution) throws Exception {
		String businessKey = execution.getProcessBusinessKey();
		logger.info("授信编号{}",businessKey);
		if(StringUtils.isEmpty(businessKey)){
			logger.error("授信编号不存在");
			throw new Exception("授信编号不存在");
		}
		CreditApplyInfoDto creditApplyInfo = new CreditApplyInfoDto();
		creditApplyInfo.setCreditApplyId(businessKey);
		creditApplyInfo = creditApplyInfoService.searchCreditApplyInfoByKey(creditApplyInfo);
		if(creditApplyInfo != null){
			if(creditApplyInfo.getApplyPersonType()
					.equals(CreditConstants.APPLY_PERSON_TYPE.MERCHANT)){//企业授信
				CreditLimitDto creditLimit = new CreditLimitDto();
				creditLimit.setCreditQuota(creditApplyInfo.getCredApprAmt());
				//申请审批通过之后一年
				creditLimit.setCreditBeginDate(new Date());
				creditLimit.setCreditEndDate(DateUtils.addMonths(new Date(), 12));
				creditLimit.setMerchId(creditApplyInfo.getApplyPersonId());
				creditLimit.setCreditType(creditApplyInfo.getCreditType());
				creditLimit.setCreditTerm(12);
				ResultDto<Boolean> result=creditLimitService.grantCreditLimit(creditLimit , 
							CreditConstants.CREDIT_BUSS_TYPE.INIT , businessKey);
				if(result==null||!result.isSuccess()||!result.getData()){
					logger.error(result.getMsg());
					throw new Exception(result.getMsg());
				}
				
				//更新法人代表基本信息及账户信息
				updateLegalPeronInfo(creditApplyInfo);
			}else{//个人授信
				CreditUserLimitDto creditLimit = new CreditUserLimitDto();
				creditLimit.setCreditLimit(creditApplyInfo.getCredApprAmt());
				//申请审批通过之后一年
				creditLimit.setCreditBeginDate(new Date());
				creditLimit.setCreditEndDate(DateUtils.addMonths(new Date(), 12));
				creditLimit.setCustId(creditApplyInfo.getApplyPersonId());
				creditLimit.setCreditType(creditApplyInfo.getCreditType());
				creditLimit.setCreditTerm(12);
				ResultDto<Boolean> result=creditUserLimitService
						.grantCreditUserLimit(creditLimit, CreditConstants.CREDIT_BUSS_TYPE.INIT, businessKey);
				if(result==null||!result.isSuccess()||!result.getData()){
					logger.error(result.getMsg());
					throw new Exception(result.getMsg());
				}
				
			}
			//更新信息
			creditApplyInfo.setCredappStat("2");
			creditApplyInfoService.updateCrepAppStatByKey(creditApplyInfo);
		}else{
			logger.error("授信编号{}未找到申请信息",businessKey);
			throw new Exception("授信编号"+businessKey+"未找到申请信息");
		}
	}

	/**
	 * 更新法人代表基本信息及账户信息
	 * @param creditApplyInfo
	 * @throws Exception
     */
	private void updateLegalPeronInfo(CreditApplyInfoDto creditApplyInfo) throws Exception {
		CreditApplyInfoDetailDto detail = new CreditApplyInfoDetailDto();
		//获取明细信息
		ResultDto<CreditApplyInfoDetailDto> retDetail = creditApplyInfoService.selectCreditApplyInfoDetailById(creditApplyInfo);
		if(retDetail.isSuccess() && retDetail.getData()!=null){
			detail = retDetail.getData();
		}
		
		MerchantRelatedDto legalPersonDto = new MerchantRelatedDto();
		legalPersonDto.setMerchId(creditApplyInfo.getApplyPersonId());
		legalPersonDto.setMerchContactRela(MerchantConstants.MERCH_RELATED_TYPE.SHOP_OWNER);
		//已经存在的法人代表信息
		List<MerchantRelatedDto> existRelatedInfo = merchantService.queryMechRelatedInfo(legalPersonDto);
		legalPersonDto.setMerchContactRelaName(detail.getCredappName());
		legalPersonDto.setMerchRelatedMobile(detail.getCredappMobile());
		legalPersonDto.setMerchRelatedCertType(detail.getCredappCertType());
		legalPersonDto.setMerchRelatedCertId(detail.getCredappCertid());
		Date now = new Date();
		//如果店铺联系人表不存在法人代表信息则新增
		if(existRelatedInfo == null || existRelatedInfo.isEmpty()) {
			legalPersonDto.setCreateTime(now);
			merchantService.createMechRelated(legalPersonDto);
		}
		//如果店铺联系人表存在法人代表信息
		else {
			MerchantRelatedDto updateNameAndMobile = new MerchantRelatedDto();
			updateNameAndMobile.setMerchRelatedName(detail.getCredappName());
			updateNameAndMobile.setMerchRelatedMobile(detail.getCredappMobile());
			for(MerchantRelatedDto merchantRelatedDto : existRelatedInfo) {
				//更新指定证件类型信息
				if(merchantRelatedDto.getMerchRelatedCertType().equals("0")) {
					legalPersonDto.setPkId(merchantRelatedDto.getPkId());
					legalPersonDto.setUpdateTime(now);
					legalPersonDto.setMerchRelatedCertType("0");//身份证
					merchantService.updateMechRelated(legalPersonDto);
				}
				//更新其他类型证件信息姓名和手机号
				else {
					updateNameAndMobile.setPkId(merchantRelatedDto.getPkId());
					updateNameAndMobile.setUpdateTime(now);
					merchantService.updateMechRelated(updateNameAndMobile);
				}
			}
		}
		//更新店铺结算账户信息
		MerchantSettleAccountDto settleAccountDto = new MerchantSettleAccountDto();
		settleAccountDto.setMerchId(creditApplyInfo.getApplyPersonId());
		settleAccountDto.setMerchSettleBank(detail.getPaybankname());
		settleAccountDto.setMerchSettleAccname(detail.getPaycustname());
		settleAccountDto.setMerchSettleAccno(detail.getPayacno());
		MerchantSettleAccountDto merchantSettleAccountExist = merchantService.qryMerchantSettleAccount(settleAccountDto);
		if(merchantSettleAccountExist == null) {
			settleAccountDto.setCreateTime(now);
			settleAccountDto.setCreateBy("creditAuto");
			settleAccountDto.setUpdateTime(new Date());
			merchantService.createMerchantSettleAccount(settleAccountDto);
		}
		else {
			settleAccountDto.setUpdateTime(now);
			settleAccountDto.setUpdateBy("creditAuto");
			merchantService.updateMerchantSettleAccount(settleAccountDto);
		}
	}

}
